package pl.s7n.paint;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.event.UndoableEditEvent;
import javax.swing.undo.UndoManager;

import pl.s7n.paint.utils.SelfUpdatable;

/**
 * A customized UndoManager class. <br>
 * Has a parent reference to a SelfUpdatable object, so that when undo/redo changes occur<br>
 * it can automatically inform the parent so it could update its state (enable/disable buttons, etc).
 * 
 * @author 7
 */
public class CanvasUndoManager extends UndoManager {
  private static final long serialVersionUID = -6532448591886960098L;

  SelfUpdatable             parent;

  public CanvasUndoManager(SelfUpdatable parent) {
    this.parent = parent;
  }

  @Override
  public void redo() {
    super.redo();
    updateGui();
  }

  @Override
  public void undo() {
    super.undo();
    updateGui();
  }

  @Override
  public void undoableEditHappened(UndoableEditEvent e) {
    super.undoableEditHappened(e);
    updateGui();
  }

  @Override
  public synchronized void discardAllEdits() {
    super.discardAllEdits();
    updateGui();
  };

  private void updateGui() {
    if (parent != null) {
      parent.update();
    }
  }

  private AbstractAction undoActionListener = new AbstractAction("UndoAction") {
                                              private static final long serialVersionUID = -5720359927122299148L;

                                              @Override
                                              public void actionPerformed(ActionEvent arg0) {
                                                if (canUndo()) { // safe
                                                  undo();
                                                }
                                              }
                                            };

  private AbstractAction redoActionListener = new AbstractAction("RedoAction") {
                                              private static final long serialVersionUID = -1686428067152365354L;

                                              @Override
                                              public void actionPerformed(ActionEvent e) {
                                                if (canRedo()) { // safe
                                                  redo();
                                                }
                                              }
                                            };

  /**
   * A classic undo action.
   */
  public AbstractAction defaultUndoAction() {
    return undoActionListener;
  }

  /**
   * A classic redo action.
   */
  public AbstractAction defaultRedoAction() {
    return redoActionListener;
  }
}
